package com.edu.framework.websocket.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.lessonremind.LessonRemindRequest;
import com.edu.framework.websocket.message.lessonremind.LessonRemindVO;
import com.edu.framework.websocket.message.timetable.TimetableRequest;
import com.edu.framework.websocket.message.timetable.TimetableVO;
import com.edu.framework.websocket.service.LessonRemindService;
import com.edu.framework.websocket.service.TimetableService;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
@Component
public class LessonRemindRequestHandler implements IHandler<LessonRemindRequest> {

    @Resource
    private LessonRemindService wsLessonRemindService;

    @Override
    public void execute(WebSocketSession session, LessonRemindRequest message) {
        if (message == null) {
            return;
        }
        Map<String, String> data = message.getData();
        Long classId = Optional.ofNullable(data.get(LessonRemindRequest.CLASS_ID_KEY))
            .filter(StrUtil::isNotBlank)
            .map(Long::parseLong)
            .orElseGet(() -> null);

        Response<LessonRemindVO> response = null;
        if (Objects.isNull(classId)){
            response = Response.fail(LessonRemindRequest.TYPE, "班级id不能同时为空");
        } else {
            response = wsLessonRemindService.nowLessonRemind(classId);
            log.info("响应：{}", JSONObject.toJSONString(response));
        }

        try {
            WebSocketHolder.send(session,response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getType() {
        return LessonRemindRequest.TYPE;
    }
}
